<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Model\Admin;

use App\Model\Model;
use Carbon\Carbon;
use Hyperf\Database\Model\Relations\HasMany;

/**
 * @property int $id 部门id
 * @property int $pid 父部门id
 * @property string $ancestors 祖级列表
 * @property string $name 部门名称
 * @property int $order_num 显示顺序
 * @property string $leader 负责人
 * @property string $phone 联系电话
 * @property string $email 邮箱
 * @property string $status 部门状态（0正常 1停用）
 * @property string $del_flag 删除标志（0代表存在 2代表删除）
 * @property string $created_by 创建者
 * @property Carbon $created_at 创建时间
 * @property string $updated_by 更新者
 * @property Carbon $updated_at 更新时间
 */
class Dept extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'dept';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'pid', 'ancestors', 'name', 'order_num', 'leader', 'phone', 'email', 'status', 'del_flag', 'created_by', 'created_at', 'updated_by', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'pid' => 'integer', 'order_num' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    /**
     * 获取修改者的姓名.
     *
     * @param string $value
     * @return string
     */
    protected array $appends=[
        "create_name",
        "update_name"
    ];

    public function getCreateNameAttribute($value)
    {
        $create_name = '未知';
        $admin_id = $this->created_by;
        if ($admin_id) {
            $create_name = Admin::query()->where('id', $admin_id)->value('nickname');
        }
        return $create_name;
    }
    public function getUpdateNameAttribute($value)
    {
        $update_name = '未知';
        $admin_id = $this->updated_by;
        if ($admin_id) {
            $update_name = Admin::query()->where('id', $admin_id)->value('nickname');
        }
        return $update_name;
    }

    public function children(): HasMany
    {
        return $this->hasMany(self::class,'pid','id')->select(['id','pid','name as title']);
    }
}
